// const nodemailer = require("nodemailer");
const logger = require('../../utils/logger-util');
const redis = require('../../redis/index');
const { SEND_EMAIL_TYPE } = require('../../constants/system/email-constants');
const { sendEmail } = require('../../utils/emailsend-util');

// 发送
exports.emailSend = (req, res) => {
    const emailInfo = req.body;
    let code = Math.random().toString(16).slice(2, 8).toUpperCase();
    let sendMailText = '';
    for(let key in SEND_EMAIL_TYPE) {
        if(SEND_EMAIL_TYPE[key].value === emailInfo.sendType) {
            sendMailText = `【Away 博客】您正在${SEND_EMAIL_TYPE[key].desc}，验证码为：${code} ，10分钟内有效。如非本人操作可忽略此信息。`
        }
    };
    sendEmail({
        eMail: emailInfo.eMail,
        text: sendMailText,
        html: emailInfo.html || ''
    }).then(async info => {
        // 六位数随机验证码生成
        let emailKey = `/${emailInfo.sendType}-${emailInfo.eMail}-emailCode`;
        // 如果有之前发送的验证码 先删除
        let resEmailKey = await redis.getValue(emailKey);
        resEmailKey && await redis.deleteValue(emailKey);
        // 验证码添加redis缓存 10分钟有效期 key:类别-邮箱名-emailCode
        redis.setValue(emailKey, JSON.stringify({emailCode:code}), 600);
        logger.info(`【邮箱】${info.accepted} 【请求验证码】${code}`);
        res.sendResultAto(null, 200, '发送成功');
    }).catch(error => {
        res.sendResultAto(null, 401, '发送失败，请联系管理员');
        logger.error(error);
    })
};